import glob
import os
import config_setting

from util_slash import f_win, f_unix
from util_ssh import execute_commands
from config_setting import nas_path_mapping

exclude_list = [
    "_gsdata_"
]

# hostname = "diskstation2"
# port = 22
# username = "admin"
# password = "mjm19831119"

def check_symbols(left_side_path, sync_suffix, symbol_folder):
    # base_path = rf"\\diskstation2\{side_name}"
    print(f"checking {left_side_path}...")

    folder_list = glob.glob(f"{left_side_path}\*{sync_suffix}")
    file_list = glob.glob(f"{left_side_path}\*{sync_suffix}.*")
    folder_list.extend(file_list)

    if not os.path.isdir(rf'{left_side_path}\{symbol_folder}') and os.path.dirname(rf'{left_side_path}\{symbol_folder}') != "":
        os.makedirs(rf'{left_side_path}\{symbol_folder}')
    symbol_lists = glob.glob(rf'{left_side_path}\{symbol_folder}\*')
    symbol_lists = list(filter(lambda x: f_unix(x).split("/")[-1] not in exclude_list, symbol_lists))

    symbol_name_lists = [f_unix(x).split("/")[-1] for x in symbol_lists]
    folder_name_lists = [f_unix(x).split("/")[-1] for x in folder_list]

    newly_sync_list = list(set(folder_name_lists) - set(symbol_name_lists))
    removal_sync_list = list(set(symbol_name_lists) - set(folder_name_lists))

    find_invalid_symbols_command = f"find {nas_path_mapping[left_side_path]}/{symbol_folder}/ -type l -xtype l"  # 找到所有无效的符号，默认其是因为外部去除__sync所致
    command_output = execute_commands(config_setting.hostname, config_setting.port, config_setting.username, config_setting.password, [find_invalid_symbols_command],
                                      require_output=True)
    invalid_symbol_list = []
    clear_invalid_symbol_command_list = []
    if command_output:
        invalid_symbol_path_list = command_output.split("\n")
        invalid_symbol_path_list = [x for x in invalid_symbol_path_list if x]  # 去除最后的空字符
        for invalid_symbol_path in invalid_symbol_path_list:  # 逐个检查invalid_symbol，如果有对应的去除__sync的文件，则代表是手工取消同步的文件，否则是因为其他问题导致，不能盲目认为是取消同步
            folder_name = f_unix(invalid_symbol_path).split("/")[-1]
            if os.path.exists(os.path.join(left_side_path, folder_name.removesuffix(sync_suffix))):
                invalid_symbol_list.append(f_unix(invalid_symbol_path).split("/")[-1])
            else:
                print(f"\033[33m[WARNs]\033[0m: 不合理的无效链接: {invalid_symbol_path}")
                if config_setting.clear_invalid_symbols:
                    clear_invalid_symbol_command_list.append(f"find {invalid_symbol_path} -type l -delete")
    if len(clear_invalid_symbol_command_list) > 0:
        execute_commands(config_setting.hostname, config_setting.port, config_setting.username, config_setting.password, clear_invalid_symbol_command_list)

    return newly_sync_list, invalid_symbol_list, removal_sync_list
    # if len(folder_name_lists) == len(symbol_name_lists) and \
    #     len(newly_sync_list) == 0 and \
    #     len(removal_sync_list) == 0 and \
    #     len(invalid_symbol_list) == 0:
    #     print(f"\033[32m[Success]\033[0m 无问题，不用执行脚本")
    #     return None, []
    # elif len(newly_sync_list) > 0:
    #     print(f"\033[32m[Next]\033[0m 有新增待同步文件，需执行脚本")
    #     return "NEWLY", newly_sync_list
    # elif len(removal_sync_list) > 0:
    #     print(f"\033[31m[Errors]\033[0m 有去除的同步文件，需执行脚本")  # 这个一般检查不出，因为在windows上识别不出已经无效的符号链接。
    #     return "REMOVAL_not_gonna_happen", removal_sync_list
    # elif len(invalid_symbol_list) > 0:
    #     print(f"\033[32m[Next]\033[0m 有无效的符号链接（应该是手动改名导致），请执行同步脚本")
    #     return "REMOVAL", invalid_symbol_list
    # else:
    #     raise Exception("\033[31m[Errors]\033[0m 不应该到达的条件！")


if __name__ == "__main__":
    left_side_path = rf"\\diskstation2\8192G_01"
    right_side_path = rf"\\diskstation2\8192G_02"

    check_symbols(left_side_path)
    check_symbols(right_side_path)

